#include "server/model/groupmodel.hpp"
#include "db.h"
#include "public.hpp"

bool GroupModel::createGroup(Group& group) {
	char sql[SQLMAXSIZE] = { 0 };
	sprintf(sql, "INSERT INTO allgroup(groupname,groupdesc) VALUES('%s','%s')",
		group.getName().c_str(), group.getDesc().c_str());
	MySQL mySql;
	if (mySql.connect() && mySql.update(sql)) {
		group.setId(mysql_insert_id(mySql.getConnection()));
		return true;
	}
	return false;
}

bool GroupModel::addGroup(int userid, int groupid, string role) {
	char sql[SQLMAXSIZE] = { 0 };
	sprintf(sql, "INSERT INTO groupuser VALUES(%d,%d,'%s')",
		groupid, userid, role.c_str());
	MySQL mysql;
	return mysql.connect() && mysql.update(sql);
}

//查询用户所在群组信息(用户登录成功以后，需要返回给用户他拥有的群组信息)
//GroupUser和AllGroup两表的联合查询
/*
 * 先根据userid在groupuser表中查询该用户所属的群组信息
 * 再根据群组信息，查询属于该群组的所有用户的userid，并且和user表进行联合查询，查出用户的详细信息
*/
vector<Group> GroupModel::queryGroups(int userid) {
	char sql[SQLMAXSIZE];
	sprintf(sql,
		"SELECT a.id,a.groupname,a.groupdesc FROM allgroup a \ 
		INNER JOIN groupuser b ON a.id = b.groupid WHERE b.userid=%d",
		userid);
	vector<Group> groupVec;
	MySQL mysql;
	if (mysql.connect()) {
		MYSQL_RES* res = mysql.query(sql);
		if (res != nullptr) {
			MYSQL_ROW row;
			//查出userid所有的群组信息
			while ((row = mysql_fetch_row(res)) != nullptr) {
				Group group;
				group.setId(atoi(row[0]));
				group.setName(row[1]);
				group.setDesc(row[2]);
				groupVec.push_back(group);
			}
			mysql_free_result(res);
		}
	}
	//查询群组的群成员信息(groupuser表和user表的联合查询)
	for (Group& group : groupVec) {
		sprintf(sql,
			"select a.id,a.name,a.state,b.grouprole from user a \
			inner join groupuser b on b.userid = a.id where b.groupid=%d",
			group.getId());
		MYSQL_RES* res = mysql.query(sql);
		if (res != nullptr) {
			MYSQL_ROW row;
			while ((row = mysql_fetch_row(res)) != nullptr) {
				GroupUser user;
				user.setId(atoi(row[0]));
				user.setName(row[1]);
				user.setState(row[2]);
				user.setRole(row[3]);
				group.getUsers().push_back(user);
			}
			mysql_free_result(res);
		}
	}
	return groupVec;
}

//根据指定的groupid查询群组用户id列表，除userid自己，主要用户群聊业务给群组其他成员群发消息
vector<int> GroupModel::queryGroupUsers(int userid, int groupid) {
	char sql[SQLMAXSIZE] = { 0 };
	sprintf(sql, "select userid from groupuser where groupid = %d and userid != %d"
		, groupid, userid);
	vector<int> idVec;
	MySQL mysql;
	if (mysql.connect()) {
		MYSQL_RES* res = mysql.query(sql);
		if (res != nullptr) {
			MYSQL_ROW row;
			while ((row = mysql_fetch_row(res)) != nullptr) {
				idVec.push_back(atoi(row[0]));
			}
			mysql_free_result(res);
		}
	}
	return idVec;
}
